<extend name="layout/main" />

<block name="HEADER">
	<style type="text/css">
		.xw-form-formType-div{ 
			height: 100% !important;
			padding: 2px !important; 
			padding-bottom: 0 !important;
		}
		.xw-form .sections{ padding: 0 !important; }
		.xw-form .xw-form-table .sections>.table-cell .table-title{
		    text-align: center;
		    background: #f9f9f9;
		    border: 1px solid #e6e6e6;
		    border-right: none;
		    line-height: 28px;
		}
		.xw-form .xw-form-table .sections>.table-cell .table-input{
			width: calc(100% - 65px) !important;
		}
		.xw-form .xw-form-table .sections>.table-cell:last-child .table-input{
			width: 100%  !important;
		}
		.xw-form .xw-form-table .sections>.table-cell{
		    min-height: 30px;
		    margin-bottom: 2px;
		    width: 48% !important;
		}
		#shopText{ color: #FF0000; line-height: 30px; font-size: 10px; }
		#tcGrid  .layui-table-view .layui-table td .layui-table-cell{
			height: auto;
			min-height: 30px;
			white-space: break-spaces;
			line-height: 24px;
			padding: 5px 3px;
		}
		#settlegoodsGrid  .layui-table-total .layui-table-cell{
			color: #FF0000 !important;
		}
		.btnMore .layui-nav-child{
			overflow: auto;
   	 		max-height: 400px;
		}
		#grid .layui-select-title{
			width: 100px;
		}
		#grid .layui-table-tool-temp span{
			display: none;
		}
		#grid .layui-table-tool-temp .xw_grid_head{
			margin-left: 0 !important;
			display: flex;
		}
		#grid .layui-table-tool-temp .xw_grid_head .layui-unselect{
			margin-right: 5px;
		}
		#grid .layui-select-title input{
			background: #ffffff;
			color: #000;
		}
		#grid .layui-select-title input::-webkit-input-placeholder{
			color: #000;
		}
	</style>
</block>

<block name="CONTENT">
	<div class="wrapper layui-tab  layui-tab-brief">
		<!--<div class="panel-heading"> </div>-->
		<ul class="layui-tab-title">
			<li class="layui-this">系统开单</li>
			<button class="layui-btn layui-btn-normal layui-btn-sm" 
				style="float: right;margin: 5px;margin-right: 20px;"
				onclick="page.tobill()"
				>购买套餐</button>
       	</ul>
		<div class="content" style="padding: 10px;">
			<div style="height: 100%;width:calc(66% - 10px);float: left;margin-right: 10px;">
				
				<!--用户信息-->
				<div style="display: flex;width: 100%;border:1px solid #dcdcdc;height: 197px;">
					<div style="flex: 2;width: 55%;">
						<control:form id="form"  />
					</div>
					<div style="flex: 1;width: 45%;padding-top: 2px;padding-right: 2px;height: calc(100% - 2px);">
						<control:grid id="tcGrid" padding="0" height="100%" />
					</div>
				</div>
				
				<!--结算列表-->
				<div style="margin: 5px 0;height: calc(100% - 250px);">
					<control:grid id="settlegoodsGrid" padding="0" height="100%" />
				</div>
				
				<!--按钮行-->
				<div class="xw-form" style="height: auto;">
					<div class="xw-btnRow" style="text-align: right;display: flex;">
						<div class="table-cell" style="width:60%;display: flex;line-height: 28px;">
	                		<div class="table-title" style="width:70px;">订单备注：</div>
	                        <div class="table-input " style="width:calc(100% - 80px);">
	                        	<input type="text" class="layui-input" value="" id="orderRemarks" >
	                        </div>
	                    </div>
						<div style="flex: 1;">
							<button type="button" class="layui-btn layui-btn-normal layui-btn-sm" onclick="page.save()"  style="background:#c55858;">结算</button> 
							<button type="button" class="layui-btn layui-btn-normal layui-btn-sm"  style="background:#F0AD4E;" onclick="page.reload()">刷新</button>
						</div>
					</div>
				</div>
				
			</div>
			<div style="height: 100%;width: 34%;float: left;border:1px solid #dcdcdc;" id="detailedInfoForm">
				<control:grid id="grid" padding="0" height="100%" />
			</div>
		</div>
	</div>
	
	
	
	<script id="tplBtns" type="text/html">	
		<select name="{{name}}" style="display: none;" lay-filter="{{name}}">
          	<option value="">{{title}}</option>
          	{{each data as val}}
	          	<optgroup label="{{val.name}}">
	          	 	{{each val.childs as v }}
	            	<option value="{{v.id}}">{{v.name}}</option>
	              	{{/each}}
	          	</optgroup>
          	{{/each}}
        </select>
	</script>
	
</block>


<block name="FOOTER">
	<script type="text/javascript">
		var page = (function(ns){

            //页面初始化
            ns.init=function(){
            	
            	grid.queryFront(function(res){
					res.push({"field":"type","opera":"<>","value": 1 });
					return res;
				});
            	
            	
            	//选择用户
				layui.selectTable.render({
	                elem: $("input[name='nickname']"),  //定义输入框input对象
	                gridId: 'selectUserGrid',
	                done: function (elem, data) {
	                	form.setFormValue(data[0]);
	                	ns.userInfo = data[0];
	                	$("#shopText").html('总到店'+data[0].shop_num+'次，距今'+data[0].day+'天未到店')
	                	tcGrid.load([{"field":"uid","opera":"=","value":form.getValue('uid')}]);
	                	settlegoodsGrid.load();
	                }
	           	});
	           	
	           	//监听输入
	           	settlegoodsGrid.input(ns.compute);
	           	
	           	//加载按钮分类
	           	ns.loadbtns();
            }
            
            //加载按钮分类
			ns.loadbtns = function(){
				$.ajaxs('/admin/v1/goods_cate/getGoodsCates').then(function(res){
		        	$("#grid .xw_grid_head").append( template('tplBtns',{
		        		name:'service',
		        		title:"服务分类",
		        		data:res.data.service
		        	}) );
		        	$("#grid .xw_grid_head").append( template('tplBtns',{
		        		name:'goods',
		        		title:"商品分类",
		        		data:res.data.goods
		        	}) );
		        	layui.form.render(null,null,'#grid');
		        	layui.form.on('select(service)', function(data){
  						var search = grid.$search.getData();
  						search.push({opera: "=", field: "type", value: 2});
  						if(data.value){
  							search.push({opera: "=", field: "cate_id", value: data.value});
  						}
  						grid.load(search);
  						$("#grid select[name='goods']").val('');
					});
					layui.form.on('select(goods)', function(data){
  						var search = grid.$search.getData();
  						search.push({opera: "=", field: "type", value:0});
  						if(data.value){
  							search.push({opera: "=", field: "cate_id", value: data.value});
  						}
  						grid.load(search);
  						$("#grid select[name='service']").val('');
					});
				});
			}
			
			//刷新
			ns.reload = function(){
				tcGrid.load();
				settlegoodsGrid.load();
				$("#orderRemarks").val('')
			}
			
			//自定义单元格的值
			ns.templet = function(e){
				if(e.data.is_proj ==  1){
					return "<em style='color:#FF0000;'>"+e.value+"</em>";
				}
				return e.value;
			}
			
			//自定义单元格的值
			ns.templet2 = function(e){
				if(e.data.is_proj ==  1 && e.data.is_yg_proj !=1){
					return '<div class="select-search-body" style="margin-top: 2px;"> <div class="select-search-input" type="search" form-datatype="search" onvalclick="page.selectWorkUser()" showclosebtn="false" name="staff_name"  data-value="'+e.value+'" ignore="" errormsg="格式不正确"><span><u onclick="page.selectWorkUser()">'+e.value+'</u></span></div> <button type="button" class="select-search-icon" onclick="page.selectWorkUser()"><i class="iconfont"></i></button> </div>';
				}
				return '';
			}
			
			//限制最大输入值
			ns.limitMax = function(e){
				var rows = settlegoodsGrid.getRows();
				$.each(rows,function(i,o){
					$("#settlegoodsGrid").find('tr[data-index='+i+']').find('.xw_table_text').attr('max',o.max);
				});
			}
			
			//单击套餐项目
			ns.tcGridRowClick = function(){
				var row = tcGrid.getSelectedRows()[0];
				var rows = settlegoodsGrid.getRows();
				var specs_ids=  $.map( rows,function(h){ 
					if(h.is_yg_proj==1){
						return Number(h.specs_id) 
					}
				})
				if( specs_ids.indexOf(row.specs_id) !=-1 ){
					return false;
				}
				settlegoodsGrid.addRow([{
					proj_id:row.proj_id,
					specs_id:row.specs_id,
					goods_name:row.goods_name,
					goods_id:row.goods_id,
					specs_name:row.specs_name,
					sale_old_price:row.sale_price,
					cart_num:1,
					discounts:0,
					sale_price:0,
					staff_id:'',
					staff_name:'',
					scale:'',
					is_yg_proj:1,
					is_proj:1,
					max: row.sy_num
				}]);
				ns.limitMax();
			}
			
			//单击商品列表
			ns.gridRowClick = function(){
				var uid = form.getValue('uid');
				if(!uid){
					return $.toast(0,"请先选择用户！")
				}
				var row = grid.getSelectedRows()[0];
				var rows = settlegoodsGrid.getRows();
				var specs_ids=  $.map( rows,function(h){ 
					if(h.is_yg_proj!=1){
						return Number(h.specs_id) 
					}
				})
				if( specs_ids.indexOf(row.specs_id) !=-1 ){
					return false;
				}
				$.ajaxs('/admin/v1/order/getSettlementInfo',{
					uid:form.getValue('uid'),
					data: JSON.stringify([{
						"id":row.specs_id,
						"goods_id":row.goods_id,
						"goods_name":row.goods_name,
						"num":1
					}])
				}).then(function(res){
					settlegoodsGrid.addRow( $.map(res.data.cartInfo,function(h){
						h.staff_id = '';
						h.staff_name = '';
						h.scale = '';
						h.goods_name = h.goods.goods_name;
						h.specs_name = h.goods.specs_name;
						h.discounts = h.goods.discounts;
						h.is_yg_proj = 0;
						h.is_proj = row.type == 2 ? 1 : 0;
						h.max = row.stock;
						return h;
					}) );
					ns.limitMax();
				});
			}
			
			//计算公式
			ns.compute =function(e,data){
				var row = settlegoodsGrid.getSelectedRows()[0];
				settlegoodsGrid.update({specs_id:row.specs_id},{
					sale_price: (row.sale_old_price * row.cart_num * (row.discounts / 10)).toFixed(2)
				});
            }
			
			//删除行
			ns.deleteRow =function(){
            	settlegoodsGrid.deleteRow();
            }
			
			//选择工作人员
			ns.selectWorkUser =function(){
            	var filter = {  url : $.getModule('selectWorkUser')  }
                $.openIframe(filter,'选择工作人员',['630px', '85%']);
            }
			ns.selectWorkUserCallback = function(ids,datas){
				var row = settlegoodsGrid.getSelectedRows()[0];
				settlegoodsGrid.update({specs_id:row.specs_id},{
					staff_id: ids,
					staff_name: datas[0]['name'],
					scale: datas[0]['scale']
				});
			}
			
			//购买套餐
			ns.tobill =function(){
                var filter = {
                    url:$.getModule('package'),
                    mode:2,
                    oid:'',
                }
                $.openIframe(filter,'购买套餐',['900px', '85%']);
			}
			
			
			//结算
            ns.save =function(e){
            	var rows = settlegoodsGrid.getRows();
            	if(!rows[0]) return $.toast(0,"请先选择商品！");
            	ns.settlementInfo = {
            		uid: form.getValue('uid'),
            		groods: rows,
            		remarks: $("#orderRemarks").val(),
            	};
            	var filter = {
                    url:$.getModule('edit'),
                    mode:2,      //2编辑
                    oid:"",
                }
                $.openIframe(filter,'结算',['600px', '500px']);
            }

		    return ns;
		}({}));
		
		$(function(){ page.init() });
	</script>
</block>